package com.mszlu.blog.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mszlu.blog.dao.mapper.BannedMapper;
import com.mszlu.blog.dao.mapper.CommentMapper;
import com.mszlu.blog.dao.pojo.Banned;
import com.mszlu.blog.dao.pojo.Comment;
import com.mszlu.blog.dao.pojo.SysUser;
import com.mszlu.blog.service.CommentsService;
import com.mszlu.blog.service.SysUserService;
import com.mszlu.blog.utils.EmptyUtils;
import com.mszlu.blog.utils.UserThreadLocal;
import com.mszlu.blog.vo.*;
import com.mszlu.blog.vo.params.CommentParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Package: com.mszlu.blog.service.impl
 * @ClassName: CommentsServiceImpl
 * @Author: 陈威
 * @CreateTime: 2021/9/2 15:55
 * @Description:
 */
@SuppressWarnings("all")
@Service
public class CommentsServiceImpl implements CommentsService {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    BannedMapper bannedMapper;

    @Override
    public Result commentsByArticleId(Long id) {
        if (EmptyUtils.isEmpty(id)){
            return new Result(999, ErrorCode.ID_NULL.getMsg());
        }
        /**
         * 1. 根据文章id 查询 评论列表 从 comment 表中查询
         * 2. 根据作者的id 查询作者的信息
         * 3. 判断 如果 level = 1 要去查询它有没有子评论
         * 4. 如果有 根据评论id 进行查询 （parent_id）
         */
        List<Comment> comments = commentMapper.selectListAll(id,1);
        List<CommentVo> commentVoList = copyList(comments);


        return Result.success(commentVoList);
    }

    @Override
    public Result comment(CommentParam commentParam) {
        if (EmptyUtils.isEmpty(commentParam)){
            return new Result(999, ErrorCode.PARAM_NULL.getMsg());
        }
        SysUser sysUser = UserThreadLocal.get();
        Comment comment = new Comment();
        comment.setArticleId(commentParam.getArticleId());
        comment.setAuthorId(sysUser.getId());
        comment.setContent(commentParam.getContent());
        comment.setCreateDate(System.currentTimeMillis());
        Long parent = commentParam.getParent();
        if (parent == null || parent == 0) {
            comment.setLevel(1);
            //递增redis中的评论量
            ValueOperations<String, String> operations = redisTemplate.opsForValue();
            operations.increment(commentParam.getArticleId()+"commentCounts");
        }else{
            comment.setLevel(2);
        }
        comment.setParentId(parent == null ? 0 : parent);
        Long toUserId = commentParam.getToUserId();
        comment.setToUid(toUserId == null ? 0 : toUserId);

        this.commentMapper.insert(comment);
        return Result.success(null);
    }

    @Override
    public Result commentAll(CommentParam commentParam) {
        if (EmptyUtils.isEmpty(commentParam)){
            return new Result(999, ErrorCode.PARAM_NULL.getMsg());
        }
        PageResult<CommentDoVo> pageResult = new PageResult<>();
        try {
            Page<Comment> page = new Page<>(commentParam.getPageNo(), commentParam.getPageSize());
            IPage<Comment> commentIPage = commentMapper.findAllComment(
                    page, commentParam.getContent(), commentParam.getNickName());

            List<Comment> records = commentIPage.getRecords();
            List<CommentDoVo> list = castCommentDoVo(records);

            pageResult.setList(list);
            pageResult.setTotal(commentIPage.getTotal());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(999,"系统错误");
        }
        return Result.success(pageResult);

    }

    private List<CommentDoVo> castCommentDoVo(List<Comment>  commentList){
        List<CommentDoVo> list = new ArrayList<>();
        for (Comment comment : commentList) {
            CommentDoVo commentVo = new CommentDoVo();
            BeanUtils.copyProperties(comment,commentVo);
            String time = DateUtil.formatDateTime(new Date(comment.getCreateDate()));
            commentVo.setCreateDate(time);
            UserVo userById = sysUserService.findUserById(comment.getAuthorId());
            commentVo.setNickname(userById.getNickname());
            commentVo.setAccount(userById.getAccount());
            Banned banned = bannedMapper.selectByUid(comment.getAuthorId());
            if(banned!=null){
                commentVo.setBannedCode(banned.getBannedCode());
            }
            commentVo.setAuthorId(String.valueOf(userById.getId()));
            list.add(commentVo);
        }
        return list;
    }
    private List<CommentVo> copyList(List<Comment> comments) {
        List<CommentVo> commentVoList = new ArrayList<>();
        for (Comment comment : comments) {
            commentVoList.add(copy(comment));
        }
        return commentVoList;
    }

    private CommentVo copy(Comment comment) {
        CommentVo commentVo = new CommentVo();
        BeanUtils.copyProperties(comment,commentVo);
        commentVo.setId(String.valueOf(comment.getId()));
        //作者信息
        Long authorId = comment.getAuthorId();
        UserVo userVo = this.sysUserService.findUserById(authorId);
        commentVo.setAuthor(userVo);
        //子评论
        Integer level = comment.getLevel();
        if (1 == level){
            Long id = comment.getId();
            List<CommentVo> commentVoList = findCommentsByParentId(id);
            commentVo.setChildrens(commentVoList);
        }
        //to User 给谁评论
        if (level > 1){
            Long toUid = comment.getToUid();
            UserVo toUserVo = this.sysUserService.findUserById(toUid);
            commentVo.setToUser(toUserVo);
        }
        return commentVo;
    }

    private List<CommentVo> findCommentsByParentId(Long id) {
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getParentId,id);
        queryWrapper.eq(Comment::getLevel,2);
        return copyList(commentMapper.selectList(queryWrapper));
    }
}
